package org.bai.miaoshaproject.service.impl;

import org.bai.miaoshaproject.dao.OrderDOMapper;
import org.bai.miaoshaproject.dao.SequenceDOMapper;
import org.bai.miaoshaproject.dataobject.OrderDO;
import org.bai.miaoshaproject.dataobject.SequenceDO;
import org.bai.miaoshaproject.error.BusinessException;
import org.bai.miaoshaproject.error.EmBusinessError;
import org.bai.miaoshaproject.service.ItemService;
import org.bai.miaoshaproject.service.OrderService;
import org.bai.miaoshaproject.service.UserService;
import org.bai.miaoshaproject.service.model.ItemModel;
import org.bai.miaoshaproject.service.model.OrderModel;
import org.bai.miaoshaproject.service.model.PromoModel;
import org.bai.miaoshaproject.service.model.UserModel;
import org.bai.miaoshaproject.validator.ValidatorImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * ClassName OrderServiceImpl
 *
 * @author Bai
 * @version 1.0
 * @date 2019/6/2 0002 上午 1:49
 **/
@Service
public class OrderServiceImpl implements OrderService {

    private final ItemService itemService;

    private final UserService userService;

    private final OrderDOMapper orderDOMapper;

    private final SequenceDOMapper sequenceDOMapper;

    private final ValidatorImpl validator;

    @Autowired
    public OrderServiceImpl(ValidatorImpl validator, ItemService itemService, UserService userService, OrderDOMapper orderDOMapper, SequenceDOMapper sequenceDOMapper) {
        this.validator = validator;
        this.itemService = itemService;
        this.userService = userService;
        this.orderDOMapper = orderDOMapper;
        this.sequenceDOMapper = sequenceDOMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderModel createOrder(Integer userId, Integer itemId, Integer promoId, Integer amount) throws BusinessException {

        // 校验下单状态
        ItemModel itemModel = itemService.getItemById(itemId);
        if(itemModel == null){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "商品信息不存在");
        }

        UserModel userModel = userService.getUserById(userId);
        if(userModel == null){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "用户信息不存在");
        }

        if(amount <= 0 || amount > 99){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "数量信息不正确");
        }

        if(promoId != null) {
            PromoModel promoModel = itemModel.getPromoModel();
            if(promoModel != null) {
                if ( !promoId.equals(promoModel.getId()) ) {
                    throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "活动信息不存在");
                } else if( !promoModel.getStatus().equals(2)){
                    throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "活动未开始");
                }
            }
        }

        // 落单减库存
        boolean result = itemService.decreaseStock(itemId, amount);
        if(!result){
            throw new BusinessException(EmBusinessError.STOCK_NOT_ENOUGH);
        }
        // 订单入库
        OrderModel orderModel = new OrderModel();
        orderModel.setUserId(userId);
        orderModel.setItemId(itemId);
        orderModel.setAmount(amount);
        orderModel.setPromoId(promoId);
        if(promoId != null){
            orderModel.setItemPrice(itemModel.getPromoModel().getPromoItemPrice());
        } else {
            orderModel.setItemPrice(itemModel.getPrice());
        }
        orderModel.setOrderPrice(orderModel.getItemPrice().multiply(new BigDecimal(amount)));

        // 生成流水号
        orderModel.setId(this.generateOrderNo());
        OrderDO orderDO = this.convertFromOrderModel(orderModel);
        orderDOMapper.insertSelective(orderDO);

        // 加上商品的销量
        itemService.increaseSales(itemId, amount);

        return orderModel;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public String generateOrderNo(){
        StringBuilder stringBuilder = new StringBuilder();
        // 前8位为时间信息
        LocalDateTime now = LocalDateTime.now();
        String nowDate = now.format(DateTimeFormatter.ISO_DATE).replace("-", "");
        stringBuilder.append(nowDate);

        // 中间的6位为自增序列
        int sequence = 0;
        SequenceDO sequenceDO = sequenceDOMapper.getSequenceByName("order_info");
        sequence = sequenceDO.getCurrentValue();
        sequenceDO.setCurrentValue(sequence + sequenceDO.getStep());
        sequenceDOMapper.updateByPrimaryKeySelective(sequenceDO);
        String sequenceStr = String.valueOf(sequence);
        for(int i = 0; i < 6 - sequenceStr.length(); i++){
            stringBuilder.append("0");
        }
        stringBuilder.append(sequenceStr);
        
        // 最后的两位为分库分表
        stringBuilder.append("00");
        return stringBuilder.toString();
    }

    private OrderDO convertFromOrderModel(OrderModel orderModel){
        if(orderModel == null){
            return null;
        }
        OrderDO orderDO = new OrderDO();
        BeanUtils.copyProperties(orderModel, orderDO);
        return orderDO;
    }

}
